<?php

class ResourceController extends Controller{
	public function actionIndex(){
        $criteria=new CDbCriteria();
        $criteria->condition = 'category=:category';
        $criteria->params = array(':category'=>'file');
        $criteria->order = 'name ASC';
        $fileType = Type::model()->findAll($criteria);
        unset($criteria);
        
        $fileList =array();
        
        foreach($fileType as $k=>$v){
            $criteria=new CDbCriteria();
            $criteria->condition = 'category_id=:category_id';
            $criteria->params = array(':category_id'=>$v->id);
            $criteria->order = 'create_date DESC';
            $fileObj = File::model()->findAll($criteria);
            $fileList[$v->name] = $fileObj; 
        }
		$this->render('index',array(
            'fileType'=>$fileType,
            'fileList'=>$fileList
        ));
	}
    
    public function actionDownload(){
        if(Yii::app()->request->isPOSTRequest){
            $message = array();
            if(isset($_POST['id']) && isset($_POST['url'])){}
            if($this->fileClick($_POST['id'],$_POST['url'])){
                $message['code'] = 1;
            }else{
                $message['code'] = 0;
            }
            echo json_encode($message);
        }else{
            throw new CHttpException(400,'请求的页面不存在.');
        }
    }

	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
    
    /**
     * 文件点击下载量
     * @param type $id
     */
    public function fileClick($id,$url){
        $model=$this->loadFileModel($id);
        if($url == $model->url_address){
            $model->download_sum += 1;
            $model->save();
            return true;
        }
        return false;
    }
    
    public function loadFileModel($id){
		$model = File::model()->findByPk($id);
        if($model===null){
            return null;
        }else{
            return $model;
        }
	}
}